//
//  LGSportsSendMemberController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/8/7.
//  选择发送成员

#import "LGSportsSendMemberController.h"
#import "LGSportsSendMemberView.h"
#import "LGSportsSendMemberCell.h"
@interface LGSportsSendMemberController ()<UITableViewDelegate,UITableViewDataSource,LGSportsSendMemberViewDelegate,UITextFieldDelegate>
/**   */
@property (nonatomic , strong)LGSportsSendMemberView *headView;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *selectAllBtn;
/**   */
@property (nonatomic , strong)UILabel *numberLabel;
/**   */
@property (nonatomic , strong)UIButton *sendButton;
/**   */
@property (nonatomic , strong)NSMutableArray *dataArray;
/**   */
@property (nonatomic , strong)NSMutableArray *selectArray;
/**   */
@property (nonatomic , copy)NSString *keyword;
/**   */
@property (nonatomic , copy)NSString *pageNo;

@end

@implementation LGSportsSendMemberController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.keyword = @"";
    self.title = @"选择患者";
    [self.view addSubview:self.headView];
    [self.view addSubview:self.tableView];
    [self emptyViewWithSuperView:self.view frame:self.tableView.frame];
    [self createBottomView];
    [self requestData];
}

-(void)requestData{
    self.pageNo = @"1";
    [self.dataArray removeAllObjects];
    [self requestDataWithPage:@"1"];
}

-(void)requestMoreData{
    [self requestDataWithPage:self.pageNo];
}

-(void)requestDataWithPage:(NSString *)pageNo{
    __block NSString *currentPage = pageNo;
    [RequestUtil withPOST:@"/doctor/patient.patient/pagedList" parameters:@{@"pageNo":currentPage,@"pageSize":@"20",@"keyword":self.keyword} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if([currentPage isEqualToString:@"1"]){
            [self.dataArray removeAllObjects];
        }
        if(code == 200){
            NSArray *tempArray = returnData[@"data"];
            if(tempArray.count>0){
                self.pageNo = [NSString stringWithFormat:@"%ld",[returnData[@"current_page"] integerValue]+1];
                [self.dataArray addObjectsFromArray:tempArray];
                //全选时，新加载的数据也要选中
                if(self.selectAllBtn.selected == YES){
                    for (NSInteger i=0; i<tempArray.count; i++) {
                        NSString *patientid = LGNSString(tempArray[i][@"id"]);
                        if(![self.selectArray containsObject:patientid]){
                            [self.headView addPatient:tempArray[i]];
                            [self.selectArray addObject:patientid];
                        }
                    }
                    self.numberLabel.attributedText = [self attributeString:[NSString stringWithFormat:@"%ld",self.selectArray.count]];
                }
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        NSLog(@">>>===>>>pageNo:%@--dataArray:%@--returnDic:%@",self.pageNo,self.dataArray,returnData);
        [self.tableView reloadData];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无患者" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无患者" offset:0];
        }
    }];
}



-(void)textFieldEidtingChanged:(UITextField *)textField{
    UITextRange *range = textField.markedTextRange;
    if(range == nil){
        self.keyword = textField.text;
        [self requestData];
    }
}


//全选
-(void)selectAllBtnAction:(UIButton *)sender{
    if(sender.selected == YES){
        //取消全选
        [self.headView removeAllPatients];
        [self.selectArray removeAllObjects];
        [self.tableView reloadData];
        
    }else{
        //全选
        for (NSInteger i=0; i<self.dataArray.count; i++) {
            NSDictionary *tempDic = self.dataArray[i];
            NSString *patientid = LGNSString(tempDic[@"id"]);
            if(![self.selectArray containsObject:patientid]){
                [self.headView addPatient:tempDic];
                [self.selectArray addObject:patientid];
            }
        }
        [self.tableView reloadData];
    }
    self.numberLabel.attributedText = [self attributeString:[NSString stringWithFormat:@"%ld",self.selectArray.count]];
    sender.selected = !sender.selected;
}

//确认发放
-(void)sendButtonAction{
    if(self.selectArray.count == 0){
        [TooltipView showMessage:@"请选择要发放的患者" offset:0];
        return;
    }
    
    NSString *ids = self.selectArray[0];
    for (NSInteger i=1; i<self.selectArray.count; i++) {
        ids = [NSString stringWithFormat:@"%@,%@",ids,self.selectArray[i]];
    }
    [RequestUtil withPOST:@"/doctor/sport.plan/send" parameters:@{@"plan_id":self.planid,@"patient_ids":ids} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            if(self.sendMemberChanged){
                self.sendMemberChanged();
            }
            [TooltipView showMessage:@"发放成功" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:@"发送失败，请重试" offset:0];
    }];
}

-(void)deletePatient:(NSString *)patientid{
    [self.selectArray removeObject:patientid];
    [self.tableView reloadData];
    self.numberLabel.attributedText = [self attributeString:[NSString stringWithFormat:@"%ld",self.selectArray.count]];
    self.selectAllBtn.selected = (self.selectArray.count==self.dataArray.count)?YES:NO;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGSportsSendMemberCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(indexPath.row < self.dataArray.count){
        cell.lineView.hidden = (indexPath.row == self.dataArray.count-1)?YES:NO;
        cell.dataDic = self.dataArray[indexPath.row];
        NSString *paitentid = LGNSString(self.dataArray[indexPath.row][@"id"]);
        cell.selectBtn.selected = ([self.selectArray containsObject:paitentid])?YES:NO;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tempDic = self.dataArray[indexPath.row];
    NSString *paitentid = LGNSString(tempDic[@"id"]);
    if([self.selectArray containsObject:paitentid]){
        //取消选择
        [self.selectArray removeObject:paitentid];
        [self.headView removePatient:tempDic];
    }else{
        //选择
        [self.selectArray addObject:paitentid];
        [self.headView addPatient:tempDic];
    }
    [self.tableView reloadData];
    self.numberLabel.attributedText = [self attributeString:[NSString stringWithFormat:@"%ld",self.selectArray.count]];
//    self.selectAllBtn.selected = (self.selectArray.count==self.dataArray.count)?YES:NO;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return viewPix(15);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LGCornerHeaderView *headView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(15))];
    headView.topMargin = viewPix(8);
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return viewPix(20);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    LGCornerFooterView *footerView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(20))];
    footerView.bottomMargin = viewPix(10);
    return footerView;
}


-(NSMutableAttributedString *)attributeString:(NSString *)count{
    NSString *content = [NSString stringWithFormat:@"已选 %@ 人",count];
    NSMutableAttributedString *attrbute = [[NSMutableAttributedString alloc]initWithString:content];
    [attrbute addAttributes:@{NSFontAttributeName:LGFontWeight(15, UIFontWeightMedium),NSForegroundColorAttributeName:[UIColor colorWithString:@"#3291FF"]} range:NSMakeRange(3, count.length)];
    return attrbute;
}

#pragma mark
#pragma mark ====> 创建控件
-(NSMutableArray *)selectArray{
    if(!_selectArray){
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(LGSportsSendMemberView *)headView{
    if(!_headView){
        _headView = [[LGSportsSendMemberView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(150))];
        [_headView.searchTF addTarget:self action:@selector(textFieldEidtingChanged:) forControlEvents:UIControlEventEditingChanged];
        _headView.searchTF.delegate = self;
        _headView.delegate = self;
    }
    return _headView;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kMaxY(self.headView.frame), Screen_W, Screen_H-topBarHeight-viewPix(150)-viewPix(76)-bottomSafeBarHeight/4.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGSportsSendMemberCell class] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
    }
    return _tableView;
}

-(UIButton *)selectAllBtn{
    if(!_selectAllBtn){
        _selectAllBtn = [UIButton buttonWithTitle:@"全选" titleFont:LGFont(15) normalColor:@"#333333" selectColor:@"#333333" normalImage:@"unselect24" selectImage:@"selected24"];
        _selectAllBtn.frame = CGRectMake(viewPix(14), viewPix(20), viewPix(70), viewPix(35));
        _selectAllBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        [_selectAllBtn addTarget:self action:@selector(selectAllBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectAllBtn;
}

-(UILabel *)numberLabel{
    if(!_numberLabel){
        _numberLabel = [UILabel lableWithText:@"已选 0 人" colorString:@"#999999" textFont:LGFont(15) textAlignment:NSTextAlignmentLeft lines:1];
        _numberLabel.attributedText = [self attributeString:@"0"];
    }
    return _numberLabel;
}

-(UIButton *)sendButton{
    if(!_sendButton){
        _sendButton = [UIButton buttonWithTitle:@"确认发放" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#FFFFFF" imageName:@""];
        _sendButton.frame = CGRectMake(Screen_W-viewPix(148), viewPix(12), viewPix(128), viewPix(46));
        _sendButton.backgroundColor = [UIColor colorWithString:@"#429BFF"];
        _sendButton.cornerRidus = 10;
        [_sendButton addTarget:self action:@selector(sendButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendButton;
}

-(void)createBottomView{
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, viewPix(76)-bottomSafeBarHeight/4.0)];
    baseView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:baseView];
    [baseView addSubview:self.selectAllBtn];
    [baseView addSubview:self.numberLabel];
    [baseView addSubview:self.sendButton];
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.selectAllBtn.mas_right);
        make.centerY.equalTo(self.selectAllBtn);
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
